package com.qf.util;

import com.qf.bean.Employee;
import com.qf.bean.Menu;
import com.qf.bean.Role;
import com.qf.dao.EmployeeMapper;
import com.qf.dao.MenuMapper;
import com.qf.dao.RoleMapper;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

/**
 * 2019/11/26
 * Administrator
 * ssm1119
 * 面向对象面向君  不负代码不负卿
 */
public class MyRealm  extends AuthorizingRealm {

    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private MenuMapper menuMapper;

    @Override  //授权
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("授权开始");
         //1.得到认证通过后的用户信息
        Employee emp =(Employee) principalCollection.getPrimaryPrincipal();
        //2.权限: 角色+url
        //2.1.根据用户名查询角色
        Role role = roleMapper.selectByPrimaryKey(emp.getRoleid());
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addRole(role.getRname());//角色权限
        //2.2 请求权限
        List<Menu> permissions = menuMapper.findPermissionByRoleId(role.getRoleid());
        ArrayList permissionList = new ArrayList();
        for (Menu menu : permissions) {
              permissionList.add(menu.getPercode());
        }
        info.addStringPermissions(permissionList);

        return info;
    }

    @Override  //认证
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("认证开始");
       //1.得到用户提交的用户名和密码
        String username =(String) authenticationToken.getPrincipal();
        //2.传给数据库，进行查询
        Employee employee = employeeMapper.login(username);
        //3.判断用户是否正确
        if(employee==null){
            System.out.println("认证结束1");
            return null;
        }else{
            System.out.println("认证结束2");
            //参数:正确的用户名，密码，盐值,自定义名称
            return new SimpleAuthenticationInfo(employee,employee.getLoginpassword(), ByteSource.Util.bytes(employee.getSalt()),"myreala");
        }
    }
}
